package pl.wroc.pwr.docs.repos.webapp.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import pl.wroc.pwr.docs.repos.webapp.repo.DocumentDao;
import pl.wroc.pwr.docs.repos.webapp.web.Message.STATUS;

@WebServlet(urlPatterns="/delete-document")
public class DocumentDeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer id = Integer.parseInt(req.getParameter("id"));
		ServletContext context = getServletContext();
		DataSource ds = (DataSource) context.getAttribute("connectionPool");
		MessageQueue messages = ((MessageQueue) req.getSession().getAttribute("messages"));
		DocumentDao dao;
		Connection con = null;
		
		try {
			con = ds.getConnection();
			dao = new DocumentDao(con);
			dao.deleteDocument(id);
			messages.push(new Message(STATUS.SUCCESS, "Dokument został usunięty."));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		resp.sendRedirect("/documents");
	}
}
